package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.service.ISysLoginService;
import com.example.utils.IpUtil;
import com.example.utils.R;
import com.google.code.kaptcha.servlet.KaptchaExtend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * 登录相关
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@Controller
public class SysLoginController extends KaptchaExtend {

    private static Logger logger = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private ISysLoginService sysLoginService;

    @GetMapping(value = "getCaptchaKey")
    @ResponseBody
    public R getCaptchaKey() {
        String captchaKey = request.getSession().getId();
        R r = new R();
        r.put("captchaKey", captchaKey);
        return r;
    }

    @GetMapping(value = "captcha.jpg/{key}/{num}")
    public void captcha(@PathVariable String key, @PathVariable BigDecimal num)
            throws ServletException, IOException {
        super.captcha(request, response);
        String captcha = getGeneratedKey(request);
        System.err.println(captcha);
        redisTemplate.opsForValue().set("captcha:" + key, captcha);
        redisTemplate.expire("captcha:" + key, 5, TimeUnit.MINUTES);
    }

    /**
     * 登录
     */
    @ResponseBody
    @PostMapping(value = "login")
    public R login(@RequestHeader HttpHeaders headers, String username, String password, String captcha, String captchaKey) throws IOException {
        /*if(StringUtils.isEmpty(captcha)){
            return R.error("请输入验证码");
        }
        if(!captcha.equals(redisTemplate.opsForValue().get("captcha:" + captchaKey))){
			return R.error("验证码不正确");
		}*/
        logger.info("headers={}",JSON.toJSONString(headers));
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return R.error("账号或密码不能为空！");
        }
        String ip = IpUtil.getIpAddress(request);
        return sysLoginService.login(username,password,ip);
    }

    /**
     * 退出
     */
    @GetMapping(value = "logout")
    public String logout() {
        return "redirect:login.html";
    }

}
